package com.example.servlet.user;

import com.example.entity.Flight;
import com.example.entity.Order;
import com.example.entity.Ticket;
import com.example.entity.User;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@WebServlet("/user_order_operation")
public class uOrderOperationServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        String orderId = req.getParameter("orderId");
        String actionType = req.getParameter("actionType");
        Order order = service.getOrderById(Integer.parseInt(orderId));
        List<Ticket> tickets = service.getTicketsByOrderId(Integer.parseInt(orderId));
        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义格式化模板
        String formattedNow = now.format(formatter);  // 格式化时间
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 定义格式化模板
        DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化今天的日期
        String formattedToday = today.format(formatterDate);
        try {
            switch (actionType) {
                case "cancel":
                    Flight flight0 = service.getFlightById(order.getFlightNo());
                    if(Objects.equals(flight0.getDeparture_date(), formattedToday)){
                        LocalTime currentTime = LocalTime.now();
                        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
                        String timeStr = currentTime.format(timeFormatter);
                        LocalTime departureTime = LocalTime.parse(flight0.getDeparture_time(), DateTimeFormatter.ofPattern("HH:mm:ss"));
                        LocalTime thirtyMinutesBefore = LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm:ss")).plusMinutes(30);
                        if (departureTime.isBefore(thirtyMinutesBefore)) {
                            // 离起飞时间小于 30 分钟，执行操作
                            req.getSession().setAttribute("no_cancel", new Object());
                            resp.sendRedirect("user_order");
                            return;
                        }
                    }
                    if(Objects.equals(order.getStatusText(), "待支付")){
                        for(Ticket ticket : tickets){
                            if(Objects.equals(ticket.getSeat_type(), "经济舱")){
                                if(service.addEconomySpaceByFid(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add economy space");
                                }
                            } else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                                if(service.addBusinessSpaceByFid(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add business space");
                                }
                            }else{
                                if(service.addFirstSpaceByFid(ticket.getFlightNo())==0){
                                    throw new Exception("Failed to add first space");
                                }
                            }
                        }
                        if(service.cancelOrder(Integer.parseInt(orderId), formattedNow)==0){
                            throw new Exception("Failed to cancel order");
                        }
                    }else{
                        for (Ticket ticket : tickets) {
                            if(service.refundTicket(ticket.getId())==0){
                                throw new Exception("Failed to refund ticket");
                            }
                        }
                        if(service.refundOrder(Integer.parseInt(orderId), formattedNow)==0){
                            throw new Exception("Failed to refund order");
                        }
                    }
                    service.commit();
                    break;
                case "pay":
                    String paymentMethod = req.getParameter("paymentMethod");
                    //扣钱
                    if(service.reduceMoneyByUserIDtypeAndIDcard(user.getID_type(), user.getID_card(), order.getPrice())==0){
                        throw new Exception("Failed to reduce money");
                    }
                    //改机票状态
                    if(service.scheduledTicketStatus(Integer.parseInt(orderId))==0){
                        throw new Exception("Failed to set order id in ticket");
                    }
                    //改订单状态
                    if(service.payOrder(Integer.parseInt(orderId), formattedNow, paymentMethod)==0){
                        throw new Exception("Failed to pay order");
                    }
                    service.commit();
                    break;
                case "rebook":
                    Flight flight = service.getFlightById(order.getFlightNo());
                    String departureCity = flight.getDeparture_city();
                    String arrivalCity = flight.getArrival_city();
                    String redirectUrl = "user_flight_search?" +
                            "departureCity=" + URLEncoder.encode(departureCity, StandardCharsets.UTF_8) +
                            "&arrivalCity=" + URLEncoder.encode(arrivalCity, StandardCharsets.UTF_8) +
                            "&departureDateStr=" + formattedToday;

                    resp.sendRedirect(redirectUrl);
                    return;
                default:
                    break;
            }
            resp.sendRedirect("user_order");
        } catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("order_operation_failure", new Object());
            resp.sendRedirect("user_order");
        }
    }
}
